var sysParam = {
    baseUrl: "/param",
    entity: "sysParam",
    tableId: "sysParamTable",
    toolbarId: "toolbar",
    currentItem: {},
    corpCd:{}
};
sysParam.columns = function () {
    return [
        {
            field: 'selectItem',
            radio: true
        },{  
            title: '序号',
            formatter: function (value, row, index) {  
                return index+1;  
            }  
        }, {
            field: 'corpCd',
            title: '法人号'
        }, {
            field: 'chparakey',
            title: '参数标识'
        }, {
            field: 'chparavalue',
            title: '参数值'
        }, {
            field: 'chparadesc',
            title: '参数说明'
        },{
            field: 'chparamaintain',
            title: '是否可维护',
        	formatter: function (value, row, index) {
        		var result=''
            	if(value=='T'){
            		result='是';
            	}else{
            		result='否';
            	}
            	return  result;
           }
        },{
            field: 'chparalocale',
            title: '应用范围',
            formatter: function (value, row, index) {
        		var result=''
            	if(value=='1'){
            		result='前台';
            	}else if(value=='2'){
            		result='后台';
            	}else{
            		result='前后台都有';
            	}
            	return  result;
           }
            
        }];
};
//得到查询的参数
sysParam.queryParams = function (params) {
	if (!params)
        return {
		chparalocale:$("#chparalocale").val()
        };
    var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        limit: params.limit, //页面大小
        page: params.offset/params.limit+1, //页码
        chparalocale:$("#chparalocale").val()
    };
    return temp;
};
sysParam.responseHandler = function(response){
	if(response.code =='200'){
		sysParam.corpCd.corpCd=response.data.corpCd;
		return response.data.page;
	}
	return false;
};
sysParam.init = function () {
    sysParam.table = $('#' + sysParam.tableId).bootstrapTable({
        url: sysParam.baseUrl+'/page', //请求后台的URL（*）
    	method: 'get', //请求方式（*）
    	toolbar: '#' + sysParam.toolbarId, //工具按钮用哪个容器
    	cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true, //是否显示分页（*）
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 10, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        showColumns: false, //是否显示所有的列
        showRefresh: true, //是否显示刷新按钮
        clickToSelect: true, 
        sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        singleSelect:true,
        striped:true,
        queryParams: sysParam.queryParams,//传递参数（*）
        responseHandler:sysParam.responseHandler,
        columns: sysParam.columns()
    });
};
sysParam.select = function (layerTips) {
    var rows = sysParam.table.bootstrapTable('getSelections');
    if (rows.length == 1) {
        sysParam.currentItem = rows[0];
        return true;
    } else {
        layerTips.msg("请选中一行");
        return false;
    }
};
sysParam.refresh = function () {
    sysParam.table.bootstrapTable('refresh', sysParam.queryParams());
};


layui.use(['form', 'layedit', 'laydate', 'element'], function () {
    sysParam.init();
    var editIndex;
    //var layerTips = parent.layer === undefined ? layui.layer : parent.layer, //获取父窗口的layer对象
    var layerTips = layui.layer;
        layer = layui.layer, //获取当前窗口的layer对象
        form = layui.form,
        layedit = layui.layedit,
        laydate = layui.laydate;
    var addBoxIndex = -1;  
    var json={
			"chparalocale":"Chparalocale",              			
	}
	selectOnload({
        "json" : json,
        "isDefault" : false,
        "func":form.render,
        "length" : 1,
    });
    //初始化页面上面的按钮事件
    $('#btn_query').on('click', function () {
        sysParam.table.bootstrapTable('refresh', sysParam.queryParams());
    });
    $('#btn_add').on('click', function () {
    	var corpCd=sysParam.corpCd;
        //本表单通过ajax加载 --以模板的形式，当然你也可以直接写在页面上读取
        $.get(sysParam.entity + '/edit', null, function (form) {
            addBoxIndex = layer.open({
                type: 1,
                title: '添加系统参数',
                content: form,
                id:'lrd_role',
                btn: ['保存', '取消'],
                shade: false,
                offset: ['20px', '20%'],
                area: ['600px', '400px'],
                maxmin: true,
                yes: function (index) {
                    layedit.sync(editIndex);
                    //触发表单的提交事件
                    $('form.layui-form').find('button[lay-filter=edit]').click();
                },
                full: function (elem) {
                    var win = window.top === window.self ? window : parent.window;
                    $(win).on('resize', function () {
                        var $this = $(this);
                        elem.width($this.width()).height($this.height()).css({
                            top: 0,
                            left: 0
                        });
                        elem.children('div.layui-layer-content').height($this.height() - 95);
                    });
                },
                success: function (layero, index) {
                	 var form = layui.form;
                	 setFromValues(layero, corpCd);
                	 if(corpCd.corpCd!='1'){
                		 layero.find('input[name=corpCd]').attr("readOnly",true);
     				 }
                    editIndex = layedit.build('description_editor');
                	var json={
                			"chparavisible":"YesNo",
                			"chparamaintain":"YesNo",
                			"chparalocale1":"Chparalocale"
                	}
                	selectOnload({
            	        "json" : json,
            	        "isDefault" : false,
            	        "func":form.render,//渲染表单
            	        "length" : 3,
            	    });               	                                                        
                    form.on('submit(edit)', function (data) {
                        $.ajax({
                            url: sysParam.baseUrl,
                            type: 'post',
                            data: data.field,
                            dataType: "json",
                            success: function (data) {
                            	if(data.code=='200'){
	                                layerTips.msg('添加成功');
	                                layerTips.close(index);
	                                sysParam.refresh();
                            	}else{
                            		layerTips.msg(data.message);
	                                layerTips.close(index);
                            	}
                            }

                        });
                        //这里可以写ajax方法提交表单
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                },
                end: function () {
                    addBoxIndex = -1;
                }
            });
        });
    });
    $('#btn_edit').on('click', function () {
        if (sysParam.select(layerTips)) {
        	var result= sysParam.currentItem;
        	if(result.chparamaintain=='T'){
	            $.get(sysParam.entity + '/edit', null, function (form) {
	                layer.open({
	                    type: 1,
	                    title: '编辑系统参数',
	                    id:'lrd_role',
	                    content: form,
	                    btn: ['保存', '取消'],
	                    shade: false,
	                    offset: ['20px', '20%'],
	                    area: ['600px', '400px'],
	                    maxmin: true,
	                    yes: function (index) {
	                        layedit.sync(editIndex);
	                        //触发表单的提交事件
	                        $('form.layui-form').find('button[lay-filter=edit]').click();
	                    },
	                    full: function (elem) {
	                        var win = window.top === window.self ? window : parent.window;
	                        $(win).on('resize', function () {
	                            var $this = $(this);
	                            elem.width($this.width()).height($this.height()).css({
	                                top: 0,
	                                left: 0
	                            });
	                            elem.children('div.layui-layer-content').height($this.height() - 95);
	                        });
	                    },
	                    success: function (layero, index) {
	                        var form = layui.form;
	                        var renderForm=function(){	                        	
	                        	layero.find("select[name='chparavisible']").val(result['chparavisible']);
	                        	layero.find("select[name='chparamaintain']").val(result['chparamaintain']);
	                        	layero.find("select[name='chparalocale']").val(result['chparalocale']);
	                        	form.render();
	                        }
	                        setFromValues(layero, result);//表单赋值
	                        layero.find('#description_editor').val(result.chparadesc);
	                        editIndex = layedit.build('description_editor');
	                        layero.find('input[name=corpCd]').attr("readOnly",true);
	                        layero.find(":input[name='chparakey']").attr("readOnly",true);
	                        form.render();
	                        var json={
	                    			"chparavisible":"YesNo",
	                    			"chparamaintain":"YesNo",
	                    			"chparalocale1":"Chparalocale"
	                    	}
	                    	selectOnload({
	                	        "json" : json,
	                	        "isDefault" : false,
	                	        "func":renderForm,//渲染表单
	                	        "length" : 3,
	                	    });
	                        
	                        form.on('submit(edit)', function (data) {                     	
	                            $.ajax({
	                                url: sysParam.baseUrl+'/'+result.chparakey,
	                                type: 'put',
	                                data: data.field,
	                                dataType: "json",
	                                success: function (data) {
	                                	if(data.code=='200'){
	                                		layerTips.msg('更新成功');
		                                    layerTips.close(index);
		                                    sysParam.refresh();
		                                }else {
		                                    layerTips.msg(data.message);
		                                    layerTips.close(index);
		                                }
	                            	}
	
	                            });
	                            //这里可以写ajax方法提交表单
	                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
	                        });
	                    }
	                });
	            });
        	}else{
        		layerTips.msg("该参数不可维护");
        	}
        }
    });
    $('#btn_del').on('click', function () {
        if (sysParam.select(layerTips)) {       	
            layer.confirm('确定删除数据吗？', null, function (index) {
                $.ajax({
                    url: sysParam.baseUrl,
                    type: "DELETE",
                    contentType:"application/json",
                    data: JSON.stringify(sysParam.currentItem),
                    success: function (data) {
                        if (data.code == '200') {
                            layerTips.msg("移除成功！");
                            sysParam.refresh();
                        } else {
                            layerTips.msg(data.message);
                        }
                    }
                });
                layer.close(index);
            });
        }
    });
    
});
